package com.wkbb.basic.controller.open;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.wkbb.basic.mapper.ClassInfoMapper;
import com.wkbb.basic.mapper.StudentMapper;
import com.wkbb.basic.model.Family;
import com.wkbb.basic.service.ClassInfoService;
import com.wkbb.common.dto.basic.*;
import com.wkbb.common.handler.JsonUtil;
import com.wkbb.common.utils.RSAUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.github.pagehelper.PageInfo;
import com.wkbb.basic.model.Student;
import com.wkbb.basic.service.FamilyService;
import com.wkbb.basic.service.StudentService;
import com.wkbb.basic.service.UserOpenService;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.constants.VersionConstant;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.utils.StringUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;

import javax.validation.Valid;

/**
 * 基础模块对外接口
 */
@RestController
@Api(description = "学生模块对外接口")
@RequestMapping("/basic/{apiVersion}/open")
@Slf4j
public class StudentController {

    @Autowired
    private UserOpenService userOpenService;

    @Autowired
    private StudentService studentService;
    @Autowired
    private ClassInfoMapper classInfoMapper;
    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private FamilyService familyService;

    @ApiOperation(value = "提交学生人脸识别数据")
    @RequestMapping(value = "/insertStudentFaceRecognition", method = RequestMethod.POST)
    public ResultDTO<?> insertStudentFaceRecognition(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @Valid @RequestBody StudentFaceRecognition data) {
        try {
            log.info("***********StudentController.updateStudentNew******apiVersion:{},data:{}", JsonUtil.stringify(data));
            if (studentService.insertStudentFaceRecognition(data) > 0)
            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("***********StudentController.getStudentInfoByStudent******", e);
        }
        return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
    }

    @ApiOperation(value = "修改学生信息")
    @RequestMapping(value = "/updateStudentNew", method = RequestMethod.POST)
    public ResultDTO<?> updateStudentNew(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @Valid @RequestBody StudentInfoDto studentInfoDto) {
        try {
            log.info("***********StudentController.updateStudentNew******apiVersion:{},data:{}", JsonUtil.stringify(studentInfoDto));
            return studentService.updateStudent(studentInfoDto);
        } catch (Exception e) {
            log.error("***********StudentController.getStudentInfoByStudent******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }
    @ApiOperation(value = "添加学生")
    @RequestMapping(value = "/addStudentNew", method = RequestMethod.POST)
    public ResultDTO<StudentInfoDto> addStudentNew(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "手机号", required = true) @RequestParam(name = "mobile", required = true) String mobile,
            @ApiParam(value = "用户ID", required = true) @RequestParam(name = "userId", required = true) Long userId,
            @Valid @RequestBody StudentInfoDto studentInfoDto) {
        try {
            log.info("addStudentNew:"+JsonUtil.stringify(studentInfoDto));
            StudentInfoDto student =  studentService.addStudent(studentInfoDto,false);
            //直接绑定到当前家长下
            Family familyInfoDto = new Family();
            familyInfoDto.setMobile(mobile);
            familyInfoDto.setUserId(userId);
            familyInfoDto.setOrgId(student.getOrgId());
            familyInfoDto.setGradeId(student.getGradeId());
            familyInfoDto.setClassId(student.getClassId());
            familyInfoDto.setStudentUserId(student.getUserId());
            familyService.insert(familyInfoDto);
            return new ResultDTO<>(student);
        } catch (Exception e) {
            log.error("***********StudentController.getStudentInfoByStudent******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "查询学生信息")
    @RequestMapping(value = "/getStudentInfoByStudent", method = RequestMethod.GET)
    public ResultDTO<List<StudentInfoDto>> getStudentInfoByStudent(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "用户ID", required = true) @RequestParam(name = "userId", required = true) Long userId) {
        log.info("***********StudentController.getStudentInfoByStudent******apiVersion:{},orgId:{},userId:{}", apiVersion, orgId, userId);

        try {

            if (null == orgId || null == userId) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            List<StudentInfoDto> studentInfoDtoList = userOpenService.getStudentInfoByStudent(orgId, userId);

            return new ResultDTO<>(studentInfoDtoList);

        } catch (Exception e) {
            log.error("***********StudentController.getStudentInfoByStudent******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "根据家长ID获取学生列表接口")
    @RequestMapping(value = "/getStudentInfoByFamily", method = RequestMethod.GET)
    public ResultDTO<List<StudentInfoDto>> getStudentInfoByFamily(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "用户ID", required = true) @RequestParam(name = "userId", required = true) Long userId) {
        log.info("***********StudentController.getStudentInfoByFamily******apiVersion:{},orgId:{},userId:{}", apiVersion,  userId);
        try {
            if (null == userId) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }
            List<StudentInfoDto> studentInfoDtoList = userOpenService.getStudentInfoByFamily(userId);
            for (StudentInfoDto stu:studentInfoDtoList){
                stu.setIdCard(RSAUtil.publicEncrypt(stu.getIdCard()));
            }
            return new ResultDTO<>(studentInfoDtoList);

        } catch (Exception e) {
            log.error("***********StudentController.getStudentInfoByFamily******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "根据家长获取单个学生信息接口")
    @RequestMapping(value = "/getStudentByFamily", method = RequestMethod.GET)
    public ResultDTO<StudentInfoDto> getStudentByFamily(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学生ID", required = true) @RequestParam(name = "studentUserId", required = true) Long studentUserId,
            @ApiParam(value = "家长ID", required = false) @RequestParam(name = "familyUserId", required = false) Long familyUserId) {
        log.info("***********StudentController.getStudentByFamily******apiVersion:{},orgId:{},studentUserId:{},familyUserId:{}", apiVersion, studentUserId,familyUserId);
        try {

            if (null == studentUserId ) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            StudentInfoDto studentInfoDto = userOpenService.getStudentByFamily(studentUserId, familyUserId);
            if (studentInfoDto == null) return new ResultDTO<>(ErrorCode.FAMILY_STU_ERROR);
            return new ResultDTO<>(studentInfoDto);

        } catch (Exception e) {
            log.error("***********StudentController.getStudentByFamily******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "根据组织ID查询学生列表")
    @RequestMapping(value = "/getStudentInfoList", method = RequestMethod.GET)
    public ResultDTO<List<StudentInfoDto>> getStudentInfoList(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "组织ID", required = true, defaultValue = "1") @RequestParam(name = "orgId", required = true) Long orgId) {

        log.info("***********StudentController.getStudentInfoList******apiVersion:{},orgId:{}", apiVersion, orgId);

        try {
            if (orgId == 0) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            Map<String, Object> params = new HashMap<>(2);
            params.put("orgId", orgId);

            return new ResultDTO<>(studentService.getStudentInfoList(params));
        } catch (Exception e) {
            log.error("***********StudentController.getStudentInfoList******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "根据班级查询学生列表")
    @RequestMapping(value = "getStudentInfoListByClassId", method = RequestMethod.GET)
    public ResultDTO<List<StudentInfoDto>> getStudentInfoListByClassId(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
            @ApiParam(value = "班级ID", required = true, defaultValue = "1") @RequestParam(name = "classId", required = true) Long classId) {
        log.info("***********StudentController.getStudentInfoListByClassId******apiVersion:{},orgId:{},classId:{}", apiVersion, orgId, classId);

        try {
            Map<String, Object> params = new HashMap<>(2);
            params.put("orgId", orgId);
            params.put("classId", classId);

            return new ResultDTO<>(studentService.getStudentInfoListByClassId(params));
        } catch (Exception e) {
            log.error("***********StudentController.getStudentInfoListByClassId******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "多条件查询学生分页列表")
    @RequestMapping(value = "/getStudentPageList", method = RequestMethod.GET)
    public ResultDTO<PageInfo<StudentInfoDto>> getStudentPageList(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "用户ID", required = false) @RequestParam(name = "userId", required = false) Long userId,
            @ApiParam(value = "学号", required = false) @RequestParam(name = "studentNo", required = false) String studentNo,
            @ApiParam(value = "学生姓名", required = false) @RequestParam(name = "name", required = false) String name,
            @ApiParam(value = "性别", required = false) @RequestParam(name = "sex", required = false) String sex,
            @ApiParam(value = "手机号", required = false) @RequestParam(name = "mobile", required = false) String mobile,
            @ApiParam(value = "学校ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "年级ID", required = false) @RequestParam(name = "gradeId", required = false) Long gradeId,
            @ApiParam(value = "班级ID", required = false) @RequestParam(name = "classId", required = false) Long classId,
            @ApiParam(value = "页码", required = false) @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = false) @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize
    ){
        Map<String,Object> params=new HashMap<>();
        params.put("userId",userId);
        params.put("studentNo",studentNo);
        params.put("name",name);
        params.put("sex",sex);
        params.put("mobile",mobile);
        params.put("orgId",orgId);
        params.put("gradeId",gradeId);
        params.put("classId",classId);
        return new ResultDTO<>(userOpenService.getStudentPageList(params,pageNo,pageSize));
    }

    @ApiOperation(value = "根据家长手机和学生姓名查询学生信息")
    @RequestMapping(value = "/getStudentInfoByMobile", method = RequestMethod.GET)
    public ResultDTO<StudentInfoDto> getStudentInfoByMobile(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "家长手机号", required =true) @RequestParam(name = "mobile", required = true) String mobile,
            @ApiParam(value = "学生姓名", required =true) @RequestParam(name = "userName", required = true) String userName

    ){
        if (null == mobile || null == userName) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }
        Map<String,Object> params=new HashMap<>();
        params.put("mobile",mobile);
        params.put("userName",userName);
        return new ResultDTO<>(studentService.getStudentInfoByMobile(params));
    }

    @ApiOperation(value = "根据卡号查询学生信息")
    @RequestMapping(value = "/getStudentInfoByCardNo", method = RequestMethod.GET)
    public ResultDTO<McStudentInfoDto> getStudentInfoByCardNo(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "学生卡号", required =true) @RequestParam(name = "cardNo", required = true) String cardNo){

        log.info("StudentController-getStudentInfoByCardNo---orgId:{},cardNo:{}",orgId,cardNo);

        try {
            Map<String,Object> params = new HashMap<>(3);
            params.put("orgId", orgId);
            params.put("cardNo", cardNo);

            return new ResultDTO<>(studentService.getByCardNo(params));
        } catch (Exception e) {
            log.error("***********StudentController.getStudentInfoByCardNo******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "根据学号查询学生信息")
    @RequestMapping(value = "/getStudentByStudentNo", method = RequestMethod.GET)
    public ResultDTO<StudentInfoDto> getStudentByStudentNo(
    		 @ApiParam(value = "学校ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
             @ApiParam(value = "学生ID", required = false) @RequestParam(name = "studentId", required = false) Long studentId,
             @ApiParam(value = "用户ID", required = false) @RequestParam(name = "userId", required = false) Long userId,
            @ApiParam(value = "学号", required =false) @RequestParam(name = "studentNo", required = false) String studentNo){

        log.info("StudentController-getStudentByStudentNo---orgId:{},userId:{},studentNo:{}",orgId,studentNo);

        try {
            Map<String,Object> params = new HashMap<>(3);
            params.put("orgId", orgId);
            params.put("userId", userId);
            params.put("studentId", studentId);
            params.put("studentNo", studentNo);

            return new ResultDTO<>(studentService.getStudentInfoByMapParams(params));
        } catch (Exception e) {
            log.error("***********StudentController.getStudentByStudentNo******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "根据年级查询学生列表")
    @RequestMapping(value = "/getGradeStudentList", method = RequestMethod.GET)
    public ResultDTO<List<StudentInfoDto>> getGradeStudentList(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "年级ID", required = true) @RequestParam(name = "gradeId", required = true) Long gradeId,
            @ApiParam(value = "性别", required = false) @RequestParam(name = "sex", required = false) String sex) {
        log.info("***********StudentController.getGradeStudentList******orgId:{},gradeId:{} sex:{}", orgId, gradeId, sex);

        try {
            if (null == orgId || null == gradeId) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            Map<String, Object> params = new HashMap<>(2);
            params.put("orgId", orgId);
            params.put("gradeId", gradeId);
            params.put("sex", sex);

            return new ResultDTO<>(studentService.getStudentInfoList(params));
        } catch (Exception e) {
            log.error("***********StudentController.getGradeStudentList******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "家长解除绑定")
    @RequestMapping(value = "/unbindStudent", method = RequestMethod.POST)
    ResultDTO<StudentInfoDto> unbindStudent(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学生ID", required = true) @RequestParam(name = "studentId", required = true) Long studentId,
            @ApiParam(value = "用户ID", required = true) @RequestParam(name = "userId", required = true) Long userId){
        try {
            if (studentId == null) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }
            //绑定学生
            Map<String,Object> fmap = new HashMap<>();
            fmap.put("studentId", studentId);
            fmap.put("userId", userId);
            Family family = familyService.getByMapParams(fmap);
            if(null != family){
                //解除绑定
                familyService.deleteByPrimaryKey(family.getId());
                return new ResultDTO<>();
            }
            //该学生未绑定
            return new ResultDTO<>(ErrorCode.FAMILY_STU_ERROR);
        } catch (Exception e) {
            log.error("***********StudentController.getStudentInfoListByClassId******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "家长绑定学生")
    @RequestMapping(value = "/bindStudent", method = RequestMethod.POST)
    ResultDTO<StudentInfoDto> bindStudent(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学号", required = false) @RequestParam(name = "studentNo", required = false) String studentNo,
            @ApiParam(value = "姓名", required = true) @RequestParam(name = "studentName", required = true) String studentName,
            @ApiParam(value = "班级邀请码", required = true) @RequestParam(name = "inviteCode", required = true) String inviteCode,
            @ApiParam(value = "手机号", required = true) @RequestParam(name = "mobile", required = true) String mobile,
            @ApiParam(value = "用户ID", required = true) @RequestParam(name = "userId", required = true) Long userId){
        try {
            if (studentName == null || inviteCode == null) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }
            Map<String,Object> map = new HashMap<>();
            map.put("inviteCode", inviteCode);
            map.put("studentNo", studentNo);
            map.put("studentName", studentName);
            List<Student> list = studentService.findListByMapParams(map);
            Student student = null;
            if (list == null || list.isEmpty()) {
//                return new ResultDTO<>(ErrorCode.STUDENT_NO_NOT_EXIST);
                //添加学生
                ClassInfo classInfo = classInfoMapper.getByMapParams(map);
                if (classInfo == null){
//                    return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
                    return ResultDTO.errorResult("用户信息填写有误，请确认后再绑定");
                }
                StudentInfoDto studentInfoDto = new StudentInfoDto();
                studentInfoDto.setOrgId(classInfo.getOrgId());
                studentInfoDto.setGradeId(classInfo.getGradeId());
                studentInfoDto.setClassId(classInfo.getId());
                studentInfoDto.setOrgName(classInfo.getOrgName());
                studentInfoDto.setGradeName(classInfo.getGradeName());
                studentInfoDto.setClassName(classInfo.getClassName());
                studentInfoDto.setName(studentName);
                Integer no = studentMapper.getClassMaxStudentNo(classInfo.getId());
                no = no == null ? 1 : no+1;
                studentInfoDto.setStudentNo(String.valueOf(no));
                studentInfoDto.setUserType(1);

                StudentInfoDto studentInfoDto1 =  studentService.addStudent(studentInfoDto,true);
                List<Student> students = new ArrayList<>();
                student = new Student();
                student.setOrgId(studentInfoDto1.getOrgId());
                student.setGradeId(studentInfoDto1.getGradeId());
                student.setClassId(studentInfoDto1.getClassId());
                student.setUserId(studentInfoDto1.getUserId());
                student.setStudentNo(studentInfoDto1.getStudentNo());
                students.add(student);
                studentMapper.insertClassStudentBatch(students);
            }else{
                if (list.size() > 1){
                    return new ResultDTO<>(ErrorCode.STUDENT_REPETITION);
                }
                student = list.get(0);
            }
            //绑定学生
            Map<String,Object> fmap = new HashMap<>();
            fmap.put("studentId", student.getUserId());
            //该学生未绑定
            if(null == familyService.getByMapParams(fmap)){
                //进行绑定
                Family familyInfoDto = new Family();
                familyInfoDto.setMobile(mobile);
                familyInfoDto.setUserId(userId);
                familyInfoDto.setOrgId(student.getOrgId());
                familyInfoDto.setGradeId(student.getGradeId());
                familyInfoDto.setClassId(student.getClassId());
                familyInfoDto.setStudentUserId(student.getUserId());
                familyService.insert(familyInfoDto);
            }else{
                return new ResultDTO<>(ErrorCode.STUDENT_NO_IS_BIND);
            }
            StudentInfoDto studentInfoDto = userOpenService.getStudentByFamily(null, student.getUserId());
            return new ResultDTO<>(studentInfoDto);
        } catch (Exception e) {
            log.error("***********StudentController.getStudentInfoListByClassId******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "扫码绑定学生")
    @RequestMapping(value = "/bindStudentByQRCode", method = RequestMethod.POST)
    ResultDTO<StudentInfoDto> bindStudentByQRCode(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "手机号", required = true) @RequestParam(name = "mobile", required = true) String mobile,
            @ApiParam(value = "用户ID", required = true) @RequestParam(name = "userId", required = true) Long userId,
            @Valid @RequestBody StudentInfoDto student){
        try {
            //绑定学生
            Map<String,Object> fmap = new HashMap<>();
            fmap.put("userId", userId);
            fmap.put("studentId", student.getUserId());
            //该学生未绑定
            if(null == familyService.getByMapParams(fmap)){
                //进行绑定
                Family familyInfoDto = new Family();
                familyInfoDto.setMobile(mobile);
                familyInfoDto.setUserId(userId);
                familyInfoDto.setOrgId(student.getOrgId());
                familyInfoDto.setGradeId(student.getGradeId());
                familyInfoDto.setClassId(student.getClassId());
                familyInfoDto.setStudentUserId(student.getUserId());
                familyService.insert(familyInfoDto);
            }else{
                return new ResultDTO<>(ErrorCode.STUDENT_NO_IS_BIND);
            }
            return new ResultDTO<>(student);
        } catch (Exception e) {
            log.error("***********StudentController.getStudentInfoListByClassId******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }
    
    private FamilyInfoDto insertFamily(FamilyInfoDto familyInfoDto, StudentInfoDto studentInfoDto, String createBy, Boolean flag) throws Exception {
        //检查必填数据
        if (familyInfoDto == null) {
            return null;
        }

        //继承学生信息
        copyStudentInfo(familyInfoDto, studentInfoDto);

        //若该家长用户不存在，新增一个用户，再添加家长信息
        if (familyInfoDto.getUserId() == null || familyInfoDto.getUserId() == 0) {
            return familyService.insertWithFamily(familyInfoDto, createBy, flag);
        } else {
            //家长用户存在情况下新增家长，取原先手机号
           // User user = userService.getByPrimaryKey(familyInfoDto.getUserId());
            //String mobile = user.getMobile();
            //familyInfoDto.setMobile(mobile);

            //否家长用户已存在，则只添加家长信息
            familyInfoDto.setId(null);
            return familyService.insertFamily(familyInfoDto, familyInfoDto.getUserId(), createBy, flag);
        }
    }
    
    
    /**
     * 家长信息加入学生信息
     *
     * @param familyInfoDto  家长信息
     * @param studentInfoDto 学生信息
     */
    private void copyStudentInfo(FamilyInfoDto familyInfoDto, StudentInfoDto studentInfoDto) {
        if (studentInfoDto.getUserId() != null) {
            familyInfoDto.setStudentUserId(studentInfoDto.getUserId());
        }
        if (!StringUtil.isNullOrBlank(studentInfoDto.getName())) {
            familyInfoDto.setStudentName(studentInfoDto.getName());
        }
        if (studentInfoDto.getOrgId() != null) {
            familyInfoDto.setOrgId(studentInfoDto.getOrgId());
        }
        if (studentInfoDto.getGradeId() != null) {
            familyInfoDto.setGradeId(studentInfoDto.getGradeId());
        }
        if (studentInfoDto.getClassId() != null) {
            familyInfoDto.setClassId(studentInfoDto.getClassId());
        }
        if (!StringUtil.isNullOrBlank(studentInfoDto.getAreaCode())) {
            familyInfoDto.setAreaCode(studentInfoDto.getAreaCode());
        }
        if (!StringUtil.isNullOrBlank(studentInfoDto.getProvinceCode())) {
            familyInfoDto.setProvinceCode(studentInfoDto.getProvinceCode());
        }
        if (!StringUtil.isNullOrBlank(studentInfoDto.getCityCode())) {
            familyInfoDto.setCityCode(studentInfoDto.getCityCode());
        }
        if (!StringUtil.isNullOrBlank(studentInfoDto.getArea())) {
            familyInfoDto.setArea(studentInfoDto.getArea());
        }
        if (!StringUtil.isNullOrBlank(studentInfoDto.getProvince())) {
            familyInfoDto.setProvince(studentInfoDto.getProvince());
        }
        if (!StringUtil.isNullOrBlank(studentInfoDto.getCity())) {
            familyInfoDto.setCity(studentInfoDto.getCity());
        }
        if (studentInfoDto.getAddr() != null) {
            familyInfoDto.setAddr(studentInfoDto.getAddr());
        }
    }
}
